﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace FC.Tools
{
    public static class WebClientHelper
    {

        static Dictionary<string, string> dic = new Dictionary<string, string>();

        static WebClientHelper()
        {
            dic.Add("authority", "sf.taobao.com");
            dic.Add("method", "GET");
            dic.Add("path", "/item_list.htm?q=&spm=a213w.3064813.9001.1");
            dic.Add("scheme", "https");
            dic.Add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            dic.Add("accept-encoding", "gzip, deflate, br");
            dic.Add("accept-language", "zh-CN,zh;q=0.8");
            dic.Add("cache-control", "max-age=0");
            dic.Add("content-type", "text/html;charset=gbk");
            dic.Add("cookie", "t=d622fb805f68e8c0c323a3d8ebd6fc2b; UM_distinctid=15f38fde49a6c2-0eaf047bee5f69-474a0521-1fa400-15f38fde49b786; cna=8NNtEttfS2gCAdvpRCqmWPEm; v=0; cookie2=181ad3d6acedcab69014e8155ac2c3bb; _tb_token_=7e33d1e853f33; uc1=cookie14=UoTcBzjQLl%2FNKw%3D%3D; CNZZDATA1253345903=300471602-1508486605-https%253A%252F%252Fwww.baidu.com%252F%7C1508751816; isg=AoSEc-JGgZrSgzVS98DszDUkVQK2Nah0iSa_OJ4lEM8SySSTxq14l7prf1fq");
            dic.Add("referer", "https://sf.taobao.com/");
            dic.Add("upgrade-insecure-requests", "1");
            dic.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
        }

        /// <summary>
        /// 通过接口提交请求的公用方法
        /// </summary>
        /// <param name="url">请求的接口地址</param>
        /// <param name="senddata">要发送的数据</param>
        /// <returns></returns>
        public static string Post(this string url, string senddata = "")
        {
            WebClient web = new WebClient();
            web.SetHeaders(dic);
            var apiurl = new Uri(url);
            string sendstr = senddata;
            var arr = web.UploadData(apiurl, Encoding.Default.GetBytes(sendstr));
            return Encoding.GetEncoding("gbk").GetString(arr);
        }

        /// <summary>
        /// 设置请求头
        /// </summary>
        /// <param name="web"></param>
        /// <param name="dictionary"></param>
        public static void SetHeaders(this WebClient web, Dictionary<string, string> dictionary)
        {
            // 循环添加请求头
            foreach (var item in dictionary)
            {
                web.Headers.Add(item.Key, item.Value);
            }
        }
    }
}
